<?php
/**
 * Description: 多贝进出课堂回调
 * User: devforma
 * Date: 16/7/19
 * Time: 17:15
 */

class DuobeiClassCallback implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        if ($this->validate($queryArgs) && $queryArgs['type'] === '2' && $queryArgs['role'] === 'student'
            && filter_var($queryArgs['userId'], FILTER_VALIDATE_INT) !== false
            && ($info = $this->getCourseInfoByRoomId($queryArgs['roomId']))) {

            $exists = $cmsdb->getVar('SELECT `id` FROM `data_liveclass_grade` WHERE `user_id`=:uid AND `class_id`=:cid LIMIT 1',
                array(':uid' => $queryArgs['userId'], ':cid' => $info->class_id));

            if (empty($exists)) {
                $cmsdb->insert('data_liveclass_grade', array(
                    'course_id' => $info->course_id,
                    'class_id' => $info->class_id,
                    'lector_id' => $info->lector_id,
                    'user_id' => $queryArgs['userId'],
                    'grade_score' => 0,
                    'is_openclass' => $info->type_id == '1',
                    'enter_time' => $queryArgs['enterTime'],
                    'comment' => ''
                ));
            }

            return 'ok';
        }

        return 'fail';
    }

    /**
     * 通过roomid获取课程课堂信息
     *
     * @param string $roomId 多贝roomid
     * @return object|null
     */
    private function getCourseInfoByRoomId($roomId) {
        global $cmsdb;

        $cacheKey = 'func:getCourseInfoByRoomId'.$roomId;
        if (($info = cacheGet($cacheKey)) == null) {
            $sql = 'SELECT r.class_id, r.course_id, co.type_id, c.lector_id 
            FROM `data_live_class` AS c, `relationship_live_class_and_course` AS r, `data_live_course` AS co 
            WHERE c.id = r.class_id AND r.course_id=co.id AND room_id=:room_id LIMIT 1';
            $info = $cmsdb->getRow($sql, [':room_id' => $roomId]);

            cacheAdd($cacheKey, $info, 12*60*60);
        }

        return $info;
    }

    /**
     * 校验请求的有效性
     *
     * @param array $params 请求参数
     * @return bool
     */
    private function validate($params) {

        $originalSign = $params['sign'];
        unset($params['sign']);

        ksort($params);

        $paramStr = '';

        foreach($params as $key => $value) {
            $paramStr .= (strval($key).'='.strval($value).'&');
        }

        return $originalSign == md5(rtrim($paramStr, '&').'771f3c17303c49f6a8dc3e3ffbf41990');
    }
}